package com.ww.sound_emission.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ww.sound_emission.domain.MinioUploads;
import com.ww.sound_emission.mapper.MinioUploadsMapper;
import com.ww.sound_emission.service.MinioUploadsService;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
* @author 96901
* @description 针对表【minio_uploads】的数据库操作Service实现
* @createDate 2025-01-18 20:50:39
*/
@Service
public class MinioUploadsServiceImpl extends ServiceImpl<MinioUploadsMapper, MinioUploads>
    implements MinioUploadsService {



    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    /**
     * 列出 Bucket 中的所有文件
     */
    public List<String> listFiles() {
        List<String> fileNames = new ArrayList<>();
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(bucketName)
                            .recursive(true)
                            .build()
            );

            for (Result<Item> result : results) {
                fileNames.add(result.get().objectName());
            }
        } catch (Exception e) {
            throw new RuntimeException("获取文件列表失败: " + e.getMessage(), e);
        }
        return fileNames;
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名称
     * @return 文件的输入流
     */
    public InputStream downloadFile(String fileName) {
        try {
            return minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("下载文件失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取文件的 Presigned URL（用于临时访问私有文件）
     *
     * @param fileName 文件名称
     * @param expiry   过期时间（单位：秒）
     * @return Presigned URL
     */
    public String getPresignedUrl(String fileName) {
        try {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("获取 Presigned URL 失败: " + e.getMessage(), e);
        }
    }












}




